import 'dart:async';

import 'package:get/get.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/events/payment_loading_event.dart';
import 'package:largefriends/events/payment_success_event.dart';
import 'package:largefriends/pages/lf_base_controller.dart';
import 'package:largefriends/service/lf_auth_service.dart';
import 'package:largefriends/utils/lf_dialog_utils.dart';

import '../../service/manager/lf_event_helper.dart';
import '../../service/manager/lf_payment_helper.dart';

toPayment() {
  Get.toNamed(LFRoute.pathPayment);
}

class LfPaymentLogic extends GetxController {
  StreamSubscription? streamSubscriptionLoading,
      streamSubscriptionPaymentSuccess;
  LoadingState loadingState = LoadingState.loading;
  LfAuthService authService = Get.find();
  RxString selectedSku = ''.obs;

  @override
  void onInit() {
    selectedSku.value = LfPaymentHelper().sku[1];
    super.onInit();
    streamSubscriptionLoading = LfEventHelper()
        .getEvent()
        .on<PaymentLoadingEvent>()
        .listen((PaymentLoadingEvent event) {
      if (event.isShow) {
        showLoading();
      } else {
        hideLoading();
      }
    });
    streamSubscriptionPaymentSuccess = LfEventHelper()
        .getEvent()
        .on<PaymentSuccessEvent>()
        .listen((PaymentSuccessEvent event) {
      hideLoading();
      Get.back();
    });
  }

  void initPayment() async {
    if (LfPaymentHelper().products.isNotEmpty) {
      loadingState = LoadingState.success;
      update();
    } else {
      loadingState = LoadingState.loading;
      update();
      await LfPaymentHelper().initStoreInfo();
      if (LfPaymentHelper().products.isNotEmpty &&
          LfPaymentHelper().products.length == LfPaymentHelper().sku.length) {
        loadingState = LoadingState.success;
        selectedSku.value = LfPaymentHelper().sku[1];
      } else {
        loadingState = LoadingState.failed;
      }
      update();
    }
  }

  void buyGold() async {
    showLoading();
    var product = LfPaymentHelper()
        .products
        .firstWhereOrNull((element) => element.id == selectedSku.value)!;
    await LfPaymentHelper()
        .buyProduct(product, authService.currentAccount!.userId!);
  }

  @override
  void onReady() {
    super.onReady();
    initPayment();
  }

  @override
  void onClose() {
    streamSubscriptionLoading?.cancel();
    streamSubscriptionPaymentSuccess?.cancel();
    super.onClose();
  }
}
